<template>
  <div v-if="!item.hidden" class="menu-wrapper">
    <!-- 没有子菜单的情况 -->
    <template
      v-if="
        noShowingChild(item.children, item) &&
        (!showingItem.children || showingItem.noShowingChildren) &&
        !item.alwaysShow
      "
    >
      <app-link :to="resolvePath(showingItem.path)">
        <el-menu-item
          :index="resolvePath(showingItem.path)"
          class="submenu-title-noDropdown"
        >
          <i class="el-icon-tickets"></i>
          {{ showingItem.meta?.title || "-" }}
        </el-menu-item>
      </app-link>
    </template>
    <!-- 有子菜单的情况 -->
    <el-submenu v-else :index="resolvePath(item.path)">
      <template slot="title">
        <Item
          v-if="item.meta"
          :icon="item.meta && item.meta.icon"
          :title="item.meta.title"
        />
      </template>
      <side-bar-item
        v-for="child in item.children"
        :item="child"
        :key="child.path"
        :base-path="resolvePath(child.path)"
        class="nest-menu"
      ></side-bar-item>
    </el-submenu>
  </div>
</template>
<script>
import { Validator } from "@bigbighu/cms-utils";
import Item from "./Item";
import path from "path";
import AppLink from "./Link";
export default {
  name: "SideBarItem",
  props: {
    item: {
      type: Object,
      required: true,
    },
    basePath: {
      type: String,
      default: "",
    },
  },
  components: {
    AppLink,
    Item,
  },
  data() {
    return {
      showingItem: "",
    };
  },
  methods: {
    // 判断当前菜单是否包含子菜单
    noShowingChild(children = [], parent) {
      // 判断子菜单是否存在数据
      const showChildren = children.filter((item) => {
        if (item.hidden) {
          return false;
        } else {
          return true;
        }
      });
      // 根据是否包含子菜单来决定页面渲染的数据
      if (showChildren.length === 0) {
        this.showingItem = { ...parent, path: "", noShowingChildren: true };
        return true;
      } else {
        return false;
      }
    },
    // 返回链接的标识
    resolvePath(routePath) {
      // 外部链接直接跳转
      // 判断跳转链接是否是外部链接
      if (Validator.isExternal(routePath)) {
        return routePath;
      }
      // 判断父级菜单的路径是否是外部链接
      if (Validator.isExternal(this.basePath)) {
        return this.basePath;
      }
      // 无外部链接标准嵌套路由路径解析
      return path.resolve(this.basePath, routePath);
    },
  },
};
</script>
<style lang="less" scope>
#app .hideSidebar .el-submenu > .el-submenu__title .iconfont {
  margin-left: 18px;
}
#app .el-menu-item {
  display: flex;
  align-items: center;
}
#app .el-menu-item [class^="el-icon-"] {
  font-size: 20px;
}
</style>
